package com.fingard.dsp.bank.directbank.spdb11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 浦发银保通批量代收付
 *
 * @author fanghh
 * @version 1.0
 */
public class SPDB11BatPayRec extends SPDB11Base implements IBatPayRec {


    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {

        return d_QryBatPayRec(p_req1998);

    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return d_BatPayRec(p_req9188);

    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return d_QryBatPayRec(p_req9198);
    }

    @SuppressWarnings("deprecation")
    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        StringBuilder sbFileContentAuth = new StringBuilder();
        String tmpReqHeaderAuth="";
        String tmpReqDataAuth="";
        Boolean iscallAuth=false;
        try {
            // 代收付文件内容
            StringBuilder sbFileContent = new StringBuilder();
            String transCode = "1006";
            String trxCode = "UBP";
            if ("1988".equals(p_reqBat.reqHeader.transType)) {
                trxCode = "UBD";
                transCode = "1008";
            }
            Date tmpPayDateTime = p_reqBat.getPayDateTime();
            //日切时间配置
            String dayChangeConfig = getBankConfig().getValueAsString("dayChangeTime");
            Date  dayChangeTime=  Format.Time8Format.parse(dayChangeConfig);
            if ((tmpPayDateTime.getHours()*60*60+tmpPayDateTime.getMinutes()*60+tmpPayDateTime.getSeconds())>=
                    (dayChangeTime.getHours()*60*60+dayChangeTime.getMinutes()*60+dayChangeTime.getSeconds())) {
                Calendar tmpPayCalendar = Calendar.getInstance();
                tmpPayCalendar.setTime(tmpPayDateTime);
                tmpPayCalendar.add(Calendar.DAY_OF_YEAR, 1);
                tmpPayDateTime = tmpPayCalendar.getTime();
            }
            String tmpPayDate = Format.Date8Format.format(tmpPayDateTime);

            //个性化签约文件的文件头
            if (getBankConfig().getValueAsBool("iscallAuth")) {
                iscallAuth=true;
                tmpReqHeaderAuth = MessageFormat.format("F※{0}※1002※{1}※※※N\n", bankFront.corpNo, p_reqBat.totalNum);
                sbFileContentAuth.append(tmpReqHeaderAuth);
            }
            // 文件头
            String tmpReqHeader = MessageFormat.format("F※{0}※{1}※{2}※{3}※{4}※{5}※※※N\n", bankFront.corpNo, transCode, p_reqBat.totalAmt, p_reqBat.totalNum, tmpPayDate, p_reqBat.totalNum);
            sbFileContent.append(tmpReqHeader);

            // 文件明细
            while (p_reqBat.readRecord()) {
                String oppAct = p_reqBat.readedDetail.payAct;
                String oppName = p_reqBat.readedDetail.payName;
                if ("1988".equals(p_reqBat.reqHeader.transType)) {
                    oppAct = p_reqBat.readedDetail.recAct;
                    oppName = p_reqBat.readedDetail.recName;
                }

                String sourceNote = oppAct;
                if (getBankConfig().getValueAsBool("fixUseCode")) {
                    if (getBankConfig().getValueAsBool("isSourceNoteCode")) {
                        sourceNote = p_reqBat.readedDetail.sourceNote;
                    } else {
                        sourceNote = p_reqBat.readedDetail.insuPolicyNum;
                    }
                }
                String payPeriod = getBankConfig().getMapValueByKey("payPeriod", p_reqBat.readedDetail.memo);
                String tmpReqBodyDetail = "";
                if ("1988".equals(p_reqBat.reqHeader.transType)) {
                    tmpReqBodyDetail = MessageFormat.format("{0}※{1}※{2}※{3}※{4}※※※\n", oppAct, p_reqBat.readedDetail.payAmount, oppName, sourceNote, p_reqBat.readedDetail.askNumber);
                } else {
                    tmpReqBodyDetail = MessageFormat.format("{0}※{1}※{2}※{3}※{4}※{5}※※※\n", oppAct, p_reqBat.readedDetail.payAmount, oppName, sourceNote, payPeriod, p_reqBat.readedDetail.askNumber);
                }
                sbFileContent.append(tmpReqBodyDetail);

                if (iscallAuth){
                    String cardType = p_reqBat.readedDetail.cardType;
                    if (StringHelper.isNullOrEmpty(cardType)) {
                        cardType = "2";
                    } else if ("1".equals(cardType)) {
                        cardType = "2";// 存折
                    } else {
                        cardType = "1";// 卡
                    }
                    String certType = convertCertTypeToBank(p_reqBat.readedDetail.certType);

                    // 签约序号※客户账户类型※客户账号※姓名※证件种类※证件号码※第三方号码※操作标志※是否浦发代销客户※备注1※备注2※密文\n
                    String tmpAuthBodyDetail = MessageFormat.format("※{0}※{1}※{2}※{3}※{4}※{5}※1※1※{6}※※\n", cardType, p_reqBat.readedDetail.payAct, p_reqBat.readedDetail.payName, certType, p_reqBat.readedDetail.certNum, sourceNote, p_reqBat.readedDetail.authCode);
                    sbFileContentAuth.append(tmpAuthBodyDetail);
                    tmpReqDataAuth = sbFileContentAuth.toString();
                    WriteBankLogLn("签约的文件内容为："+tmpReqDataAuth);
                }

            }
            String tmpReqData = sbFileContent.toString();
            WriteBankLogStep2(tmpReqData);
            // 上传文件名保存本地，查询时用
            String tmpMarkDataDir = getDataFileDirectory(tmpPayDateTime) + File.separator + "bat";
            int maxBatch = 0;
            File dataFileDir = new File(tmpMarkDataDir);
            if (dataFileDir.exists()) {
                int len = dataFileDir.listFiles().length;
                if (len > 0) {
                    if (iscallAuth) {
                        len=len/2;
                    }
                    maxBatch = len + 1;

                } else {
                    maxBatch = 1;
                }
            }
            // 文件名命名规则: UBD/UBP_保险公司编号(4位) _机构代码（4位）_日期（8位）_序号（2位）
            String tmpUpFilePrefix = trxCode + "_" + bankFront.corpNo + "_" + bankFront.org + "_" + tmpPayDate + "_" + String.format("%2s", maxBatch).replace(" ", "0");
            String tmpUpFileName = tmpUpFilePrefix + ".TXT";
            String tmpLocalMarkPath = StringHelper.trimEnd(tmpMarkDataDir, File.separator) + File.separator + p_reqBat.reqBatchNO + ".txt";
            WriteBankLogLn2("批次号映射文件路径: " + tmpLocalMarkPath);
            FileHelper.writeFile(tmpLocalMarkPath, tmpUpFilePrefix, getCharset());
            String[] upFinishRet=null;
            String[] tmpUpFilePrefixs=new String[] { "", "" };
            if (getBankConfig().getValueAsBool("iscallAuth")){
                tmpUpFilePrefixs[0] = "UBCS_" + bankFront.corpNo + "_" + bankFront.org + "_" + Format.Date8Format.format(tmpPayDateTime) + "_" + String.format("%2s", maxBatch).replace(" ", "0");
                tmpUpFilePrefixs[1]=tmpUpFilePrefix;
                upFinishRet = sendToBank(tmpPayDateTime, tmpReqData, tmpUpFilePrefixs, tmpReqDataAuth);
            }else{
                WriteBankLogLn2("批次号映射文件路径: " + tmpLocalMarkPath);
                //上送银保通服务器
                upFinishRet = sendToBank(tmpReqData, tmpPayDateTime, tmpUpFileName, p_reqBat.reqHeader.transType);
            }
            if (upFinishRet[0].length() == 0) {
                retAts.respCode = "0";
                retAts.respInfo = "文件已生成，并已上送银保通服务器";
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = "UBPD+uploaded";
                retAts.payInfoCode = "uploaded";
            } else {
                retAts.respCode = "-1";
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.respInfo = "文件上传失败，原因:" + upFinishRet[1];
                retAts.transState = "UBPD+" + upFinishRet[1];
                retAts.payInfoCode = upFinishRet[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqBat.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.reqSeqID = p_reqQryBat.reqBatchNO;
        try {
            Date tmpPaySendTime = p_reqQryBat.getBgnDateTime();
            String dayChangeConfig = getBankConfig().getValueAsString("dayChangeTime");
            Date  dayChangeTime=  Format.Time8Format.parse(dayChangeConfig);
            if ((tmpPaySendTime.getHours()*60*60+tmpPaySendTime.getMinutes()*60+tmpPaySendTime.getSeconds())>=
                    (dayChangeTime.getHours()*60*60+dayChangeTime.getMinutes()*60+dayChangeTime.getSeconds())) {
                Calendar tmpPayCalendar = Calendar.getInstance();
                tmpPayCalendar.setTime(tmpPaySendTime);
                tmpPayCalendar.add(Calendar.DAY_OF_YEAR, 1);
                tmpPaySendTime = tmpPayCalendar.getTime();
            }
            String tmpMarkDataDir = getDataFileDirectory(tmpPaySendTime) + File.separator + "bat";
            String tmpLocalMarkPath = StringHelper.trimEnd(tmpMarkDataDir, File.separator) + File.separator + p_reqQryBat.reqBatchNO + ".txt";
            WriteBankLogLn2("本地批次号映射文件路径: " + tmpLocalMarkPath);
            File localMarkFile = new File(tmpLocalMarkPath);
            if (!localMarkFile.exists()) {
                retAts.respCode = "-1";
                retAts.respInfo = "批次流水映射文件未生成，尚未回盘!";
                retAts.writeAfterDetail();
                return retAts;
            }
            String trxCode = "DBP";
            if ("1998".equals(p_reqQryBat.reqHeader.transType)) {
                trxCode = "DBD";
            }
            String tmpDownFileName = "";
            String tmpDownFilePrefix = FileHelper.readFileText(tmpLocalMarkPath, getCharset());
            if (StringHelper.hasAnyChar(tmpDownFilePrefix)) {
                tmpDownFileName = trxCode + tmpDownFilePrefix.substring(3) + ".TXT";
            } else {
                tmpDownFileName = trxCode + tmpDownFilePrefix+ ".TXT";
            }

            //获得配置文件中的传送方式，选择传输模式。
            String[] result = fetchResFromBank(tmpDownFileName, tmpPaySendTime, tmpDownFilePrefix, p_reqQryBat.reqHeader.transType);
            if ("0".equals(result[0])) {
                retAts.respCode = "0";
                StringReader strReader = new StringReader(result[1]);
                BufferedReader tmpReader = new BufferedReader(strReader);
                tmpReader.readLine();
                while (true) {
                    String eachline = tmpReader.readLine();
                    if (eachline == null) {
                        break;
                    }
                    String[] eachNodes = eachline.split("※");
                    if(eachNodes.length>5){
                        RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                        tmpRetDetail.postScript = eachNodes[6].trim();
                        tmpRetDetail.payAmount = eachNodes[1].trim();
                        if ("1988".equals(p_reqQryBat.reqHeader.transType)) {
                            tmpRetDetail.recAct = eachNodes[0].trim();
                            tmpRetDetail.recName = eachNodes[2].trim();
                        } else {
                            tmpRetDetail.payAct = eachNodes[0].trim();
                            tmpRetDetail.payName = eachNodes[2].trim();
                        }
                        String tmpRespCode = eachNodes[4].trim();
                        //DBP 表示 Down Batch Payment (批量扣款)
                        // 0-失败 1-成功
                        tmpRetDetail.result = "DBPD+" + tmpRespCode;
                        String[] bkInfo = eachNodes[5].trim().split(":");
                        if (bkInfo.length > 1) {
                            tmpRetDetail.payInfoCode = bkInfo[0];
                            tmpRetDetail.memo = bkInfo[1];
                        } else if("".equals(eachNodes[5].trim())&&"1".equals(tmpRespCode)) {
                            tmpRetDetail.payInfoCode = "0";
                            tmpRetDetail.memo = "成功";
                        }else {
                            tmpRetDetail.payInfoCode = eachNodes[5].trim();
                            tmpRetDetail.memo = eachNodes[5].trim();
                        }
                        retAts.writeRetDetail(tmpRetDetail);
                    }

                }
                tmpReader.close();
                strReader.close();
            } else {
                retAts.respCode = result[0];
                retAts.respInfo = result[1];
                retAts.writeAfterDetail();
                return retAts;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeAfterDetail();
        return retAts;
    }
}

